package com.tensquare.friend.service;

import com.tensquare.friend.dao.FriendDao;
import com.tensquare.friend.dao.NoFriendDao;
import com.tensquare.friend.pojo.Friend;
import com.tensquare.friend.pojo.NoFriend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class FriendService {
    @Autowired
    private FriendDao friendDao;
    @Autowired
    private NoFriendDao noFriendDao;

    public int save(String userid, String friendid, String type) {
        if (type.equals("1")) {
            //1.表示喜欢
            //1.1先根据userId到friendId查询是否已经添加好友
            Friend friend = friendDao.findByUseridAndFriendid(userid, friendid);
            if (friend != null) {
                return 1;
            }
            //1.2如果没添加好友，再根据friendId到userId查询是否是好友
            friend = friendDao.findByUseridAndFriendid(friendid, userid);
            //1.3再根据第二部查询数据添加好友
            if (friend == null) {
                friendDao.save(new Friend(userid, friendid, "0"));
            } else {
                friendDao.save(new Friend(userid, friendid, "1"));
                friendDao.updateIsLike("1", friendid, userid);
            }
            return 0;
        } else {
            //2.表示不喜欢
            NoFriend noFriend = noFriendDao.findByUseridAndFriendid(userid, friendid);
            if (noFriend != null) {
                return 1;
            }
            noFriendDao.save(new NoFriend(userid, friendid));
            return 2;
        }
    }

    public void deleteFriend(String id, String friendid) {
        //1.删除userid到friendid的数据
        friendDao.deleteByUseridAndFriendid(id, friendid);
        //2.修改friendid到userid的islike
        friendDao.updateIsLike("0", friendid, id);
        //3.添加到非好友数据表
        noFriendDao.save(new NoFriend(id, friendid));
    }
}
